//时间转化
function changeTime(date) {
    var json_date = new Date(date).toJSON();
    return new Date(+new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

// 评论时间格式化
function formatCommitTime(date) {
    let time = new Date(date)
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000
    } else {
        time = +time
    }
    const d = new Date(time)
    const now = Date.now()
    const diff = (now - d) / 1000
    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '昨天'
    } else if (diff < 3600 * 24 * 3) {
        return '2天前'
    } else if (diff < 3600 * 24 * 4) {
        return '3天前'
    } else if (diff < 3600 * 24 * 5) {
        return '4天前'
    } else if (diff < 3600 * 24 * 6) {
        return '5天前'
    } else if (diff < 3600 * 24 * 7) {
        return '6天前'
    } else if (diff < 3600 * 24 * 360) { //一年内
        d.getMonth() + 1 + '-' + d.getDate()
    }
    return ( //大于一年
        d.getFullYear() + '-' + d.getMonth() + 1 + '-' + d.getDate()
    )
}

//判断深浅色模式
function hexToRgb(val) { //HEX十六进制颜色值转换为RGB(A)颜色值
    // 16进制颜色值的正则
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    // 把颜色值变成小写
    var color = val.toLowerCase();
    var result = '';
    if (reg.test(color)) {
        // 如果只有三位的值，需变成六位，如：#fff => #ffffff
        if (color.length === 4) {
            var colorNew = "#";
            for (var i = 1; i < 4; i += 1) {
                colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
            }
            color = colorNew;
        }
        // 处理六位的颜色值，转为RGB
        var colorChange = [];
        for (var i = 1; i < 7; i += 2) {
            colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
        }
        var grayLevel = colorChange[0] * 0.299 + colorChange[1] * 0.587 + colorChange[2] * 0.114;
        if (grayLevel >= 192) { //浅色模式
            return '#000';
        } else {
            return '#fff';
        }
    } else {
        result = '无效';
        return {
            rgb: result
        };
    }
}

/**
 * @description: 调整颜色更亮更暗
 * @param {string} color 六位十六进制颜色
 * @param {number} range 正负数决定颜色更改-负为加深
 * @return {string} new color
 */
function adjustColor(color, range) {
    let newColor = '#';
    for (let i = 0; i < 3; i++) {
        const hxStr = color.substr(i * 2 + 1, 2);
        let val = parseInt(hxStr, 16);
        val += range;
        if (val < 0) val = 0;
        else if (val > 255) val = 255;
        newColor += val.toString(16).padStart(2, '0')
    }
    return newColor;
}

module.exports = {
    changeTime,
    formatCommitTime,
    hexToRgb,
    adjustColor,
};